<script setup>
import { ref, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { IconFile, IconFolder } from '@arco-design/web-vue/es/icon';
import { CopyFile, CopyDir, CreateDir, CreateFile, RenameFile, TreeFile } from "../../wailsjs/go/main/App";
const treeData = ref([]);
const router = useRouter();
const route = useRoute()
const treeRef = ref()
const expandedKeys = ref([])
const handleSelect = (_, { node }) => {
    if (!node.dir) {
        router.push(`/form/${node.path}`)
        return
    } else if (node.is_dir) {
        treeRef.value.expandNode(node.path, expandedKeys.value.indexOf(node.path) === -1)
    } else {
        router.push(`/template?path=${node.path}`)
    }
}
const menuActive = ref({})
const editableActive = ref("")
const getItemData = (key) => {
    const loop = (data) => {
        let result = {};
        for (let i = 0; i < data.length; i++) {
            if (data[i].path === key) {
                result = data[i];
            } else if (data[i].children) {
                result = loop(data[i].children);
            }
            if (result.path) {
                break;
            }
        }
        return result;
    }
    return loop(treeData.value);
}
const handleContextMenu = (e) => {
    let loop = 0;
    const getDataKey = (elm) => {
        if (!elm || loop > 20) {
            return ""
        }
        loop++;
        let classList = elm.getAttribute('class').split(" ")
        if (classList?.indexOf("arco-tree") > -1) {
            return ""
        } else if (classList?.indexOf("arco-tree-node") > -1) {
            return elm.getAttribute('data-key')
        } else {
            return getDataKey(elm.parentNode)
        }
    }
    e.preventDefault();
    let path = getDataKey(e.target)
    if (path) {
        menuActive.value = getItemData(path)
    } else {
        menuActive.value = {};
    }
}
const treeFieldNames = {
    title: 'name',
    key: 'path',
    isLeaf: "is_dir",
    children: 'children'
}
const loadData = () => {
    TreeFile().then(res => {
        treeData.value = res;
    })
}
loadData()
const inputNameRef = ref()
const handleInputEditable = () => {
    editableActive.value = menuActive.value.path
    nextTick(() => {
        inputNameRef.value?.focus()
    })
}
const handleInputBlur = () => {
    let filename = `${menuActive.value.dir}/${menuActive.value.name}`
    if (menuActive.value.path == "") {
        if (menuActive.value.is_dir) {
            CreateDir(filename).then(() => {
                loadData()
            })
        } else {
            CreateFile(filename).then(() => {
                loadData()
            })
        }
    } else {
        RenameFile(menuActive.value.path, filename).then(() => {
            loadData()
        })
    }
    editableActive.value = ""
}
const handleCopy = () => {
    let filename = `${menuActive.value.path}.copy`
    if (menuActive.value.is_dir) {
        CopyDir(filename).then(() => {
            loadData()
        })
    } else {
        CopyFile(filename).then(() => {
            loadData()
        })
    }
}
const handleRemove = (item) => {
    console.log(item)
}
const handleCreateDatabase = () => {
    CreateDir("test").then(() => {
        loadData()
    })
}
const handleCreateTemplate = () => {
    CreateFile(`${menuActive.value.path}/vue`).then(() => {
        loadData()
    })
}
const handleMenuSelect = (key) => {
    switch (key) {
        case 'refresh':
            loadData()
            break;
        case 'rename':
            handleInputEditable()
            break;
        case 'view':
            handleSelect([menuActive.value.path])
            break;
        case 'copy':
            handleCopy()
            break;
        case 'remove':
            editableActive.value = menuActive.value.path
            break;
        case 'create_database':
            handleCreateDatabase();
            break;
        case 'create_template':
            handleCreateTemplate();
            break;
    }
}
</script>
<template>
    <div class="w-full h-full flex flex-col">
        <div class="border-b border-color h-7">

        </div>
        <a-scrollbar class="overflow-auto w-full h-full" outer-class="w-full h-0 flex-1">
            <a-dropdown trigger="contextMenu" alignPoint class="block" position="bl" @select="handleMenuSelect">
                <a-tree ref="treeRef" :data="treeData" v-model:expanded-keys="expandedKeys"
                    :field-names="treeFieldNames" @select="handleSelect" @contextmenu="handleContextMenu" size="mini"
                    :block-node="true" :animation="false" :default-selected-keys="[route.query.path]"
                    class="h-full file-tree">
                    <template #icon="{ node }">
                        <IconFile size="14" v-if="!node.is_dir" />
                    </template>
                    <template #title="node">
                        <a-input ref="inputNameRef" v-if="editableActive == node.path" v-model="menuActive.name"
                            @blur="handleInputBlur" size="mini" class="!px-1 !h-full" />
                        <div v-else class="w-full h-full px-1">{{ node.name }}</div>
                    </template>
                </a-tree>
                <template #content>
                    <div v-if="menuActive.is_dir === true">
                        <a-doption value="view">查看连接</a-doption>
                        <a-doption value="remove">删除连接</a-doption>
                        <a-doption value="create_template">新建模板</a-doption>
                    </div>
                    <div v-if="menuActive.is_dir === false">
                        <a-doption value="view">查看模板</a-doption>
                        <a-doption value="create_template">新建模板</a-doption>
                        <a-doption value="remove">删除模板</a-doption>
                    </div>
                    <a-doption v-if="menuActive.path" value="rename">重命名</a-doption>
                    <a-doption value="create_database">新建连接</a-doption>
                    <a-doption value="refresh">刷新</a-doption>
                </template>
            </a-dropdown>
        </a-scrollbar>
    </div>
</template>